import { Card, CardValue, CardSuit, HandRank } from '../store/gameSlice';

// 创建一副牌
export const createDeck = (): Card[] => {
  const deck: Card[] = [];
  
  for (const suit of Object.values(CardSuit)) {
    for (const value of Object.values(CardValue)) {
      deck.push({ value: value as CardValue, suit });
    }
  }
  
  return deck;
};

// 洗牌
export const shuffleDeck = (deck: Card[]): Card[] => {
  const shuffled = [...deck];
  
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  
  return shuffled;
};

// 从一副牌中抽取指定数量的牌
export const drawCards = (deck: Card[], count: number): { cards: Card[], remainingDeck: Card[] } => {
  if (count > deck.length) {
    throw new Error('Not enough cards in deck');
  }
  
  const cards = deck.slice(0, count);
  const remainingDeck = deck.slice(count);
  
  return { cards, remainingDeck };
};

// 判断是否是同花
export const isFlush = (cards: Card[]): boolean => {
  if (cards.length < 5) return false;
  
  const suitCounts: { [key in CardSuit]?: number } = {};
  
  for (const card of cards) {
    suitCounts[card.suit] = (suitCounts[card.suit] || 0) + 1;
  }
  
  return Object.values(suitCounts).some(count => count >= 5);
};

// 判断是否是顺子
export const isStraight = (cards: Card[]): boolean => {
  if (cards.length < 5) return false;
  
  // 获取所有牌面值并去重
  const values = Array.from(new Set(cards.map(card => card.value))).sort((a, b) => a - b);
  
  // 检查常规顺子
  for (let i = 0; i <= values.length - 5; i++) {
    let isStraight = true;
    for (let j = 0; j < 4; j++) {
      if (values[i + j + 1] - values[i + j] !== 1) {
        isStraight = false;
        break;
      }
    }
    if (isStraight) return true;
  }
  
  // 检查A-2-3-4-5的特殊顺子
  if (values.includes(CardValue.ACE) && 
      values.includes(CardValue.TWO) && 
      values.includes(CardValue.THREE) && 
      values.includes(CardValue.FOUR) && 
      values.includes(CardValue.FIVE)) {
    return true;
  }
  
  return false;
};

// 获取所有相同面值的牌的数量
export const getValueCounts = (cards: Card[]): { [key: number]: number } => {
  const valueCounts: { [key: number]: number } = {};
  
  for (const card of cards) {
    const cardValue = card.value as number;
    valueCounts[cardValue] = (valueCounts[cardValue] || 0) + 1;
  }
  
  return valueCounts;
};

// 判断是否是对子
export const isPair = (cards: Card[]): boolean => {
  const valueCounts = getValueCounts(cards);
  return Object.values(valueCounts).some(count => count === 2);
};

// 判断是否是两对
export const isTwoPair = (cards: Card[]): boolean => {
  const valueCounts = getValueCounts(cards);
  const pairs = Object.values(valueCounts).filter(count => count === 2);
  return pairs.length >= 2;
};

// 判断是否是三条
export const isThreeOfAKind = (cards: Card[]): boolean => {
  const valueCounts = getValueCounts(cards);
  return Object.values(valueCounts).some(count => count === 3);
};

// 判断是否是葫芦
export const isFullHouse = (cards: Card[]): boolean => {
  const valueCounts = getValueCounts(cards);
  const hasThree = Object.values(valueCounts).some(count => count === 3);
  const hasPair = Object.values(valueCounts).some(count => count === 2);
  return hasThree && hasPair;
};

// 判断是否是四条
export const isFourOfAKind = (cards: Card[]): boolean => {
  const valueCounts = getValueCounts(cards);
  return Object.values(valueCounts).some(count => count === 4);
};

// 判断是否是同花顺
export const isStraightFlush = (cards: Card[]): boolean => {
  return isFlush(cards) && isStraight(cards);
};

// 判断是否是皇家同花顺
export const isRoyalFlush = (cards: Card[]): boolean => {
  if (!isStraightFlush(cards)) return false;
  
  // 检查是否包含10, J, Q, K, A
  const values = cards.map(card => card.value);
  return [CardValue.TEN, CardValue.JACK, CardValue.QUEEN, CardValue.KING, CardValue.ACE].every(
    value => values.includes(value)
  );
};

// 获取手牌等级
export const getHandRank = (cards: Card[]): HandRank => {
  if (isRoyalFlush(cards)) return HandRank.ROYAL_FLUSH;
  if (isStraightFlush(cards)) return HandRank.STRAIGHT_FLUSH;
  if (isFourOfAKind(cards)) return HandRank.FOUR_OF_A_KIND;
  if (isFullHouse(cards)) return HandRank.FULL_HOUSE;
  if (isFlush(cards)) return HandRank.FLUSH;
  if (isStraight(cards)) return HandRank.STRAIGHT;
  if (isThreeOfAKind(cards)) return HandRank.THREE_OF_A_KIND;
  if (isTwoPair(cards)) return HandRank.TWO_PAIR;
  if (isPair(cards)) return HandRank.PAIR;
  return HandRank.HIGH_CARD;
};

// 比较两手牌的大小
export const compareHands = (hand1: Card[], hand2: Card[]): number => {
  const rank1 = getHandRank(hand1);
  const rank2 = getHandRank(hand2);
  
  // 牌型等级比较
  const rankOrder = [
    HandRank.HIGH_CARD,
    HandRank.PAIR,
    HandRank.TWO_PAIR,
    HandRank.THREE_OF_A_KIND,
    HandRank.STRAIGHT,
    HandRank.FLUSH,
    HandRank.FULL_HOUSE,
    HandRank.FOUR_OF_A_KIND,
    HandRank.STRAIGHT_FLUSH,
    HandRank.ROYAL_FLUSH,
  ];
  
  const rank1Index = rankOrder.indexOf(rank1);
  const rank2Index = rankOrder.indexOf(rank2);
  
  if (rank1Index !== rank2Index) {
    return rank1Index > rank2Index ? 1 : -1;
  }
  
  // 如果牌型相同，比较高牌
  // 这里简化处理，实际应该根据牌型进行详细比较
  const values1 = hand1.map(card => card.value).sort((a, b) => b - a);
  const values2 = hand2.map(card => card.value).sort((a, b) => b - a);
  
  for (let i = 0; i < Math.min(values1.length, values2.length); i++) {
    if (values1[i] !== values2[i]) {
      return values1[i] > values2[i] ? 1 : -1;
    }
  }
  
  return 0; // 平局
};